const config = require('../src/utils/config')

const { apiPrefix } = config

let departments = [
  {
    id: 1,
    name: "总经办",
    sn: "ZONGJINGBAN:1",
    parent: {
      id: 0,
      name: '公司总部',
    },
    manager: {
      id: 1,
      name: 'Hox',
    },
    phoneNum: '18808888088',
    children: [{
      id: 2,
      name: "Test",
      sn: "TEST:2",
      parent: {
        id: 1,
        name: '总经办',
      },
      manager: {
        id: 1,
        name: 'Hox',
      },
      phoneNum: '18808888088',
    }],
  },
  {
    id: 2,
    name: "财务部",
    sn: "CAIWUBU:2",
  },
  {
    id: 3,
    name: "技术部",
    sn: "JISHUBU:3",
  },
  {
    id: 4,
    name: "人事部",
    sn: "RENSHIBU:4",
  },
]

const queryArray = (array, key, keyAlias = 'key') => {
  if (!(array instanceof Array)) {
    return null
  }
  let data

  for (let item of array) {
    if (item[keyAlias] === key) {
      data = item
      break
    }
  }

  if (data) {
    return data
  }
  return null
}

const NOTFOUND = {
  message: 'Not Found',
  documentation_url: 'http://localhost:8000/request',
}

module.exports = {

  [`GET ${apiPrefix}/departments`](req, res) {
    const { query } = req
    let { size, current, ...other } = query
    size = size || 10
    current = current || 1

    let newData = departments
    for (let key in other) {
      if ({}.hasOwnProperty.call(other, key)) {
        newData = newData.filter((item) => {
          if ({}.hasOwnProperty.call(item, key)) {
            return String(item[key]).trim().indexOf(decodeURI(other[key]).trim()) > -1
          }
          return true
        })
      }
    }

    res.status(200).json({
      code: 0,
      message: "successed",
      // data: {
      //   records: newData,
      //   total: newData.length,
      // },
      data: newData
    })
  },

  [`POST ${apiPrefix}/departments/delete`](req, res) {
    res.status(204).end()
  },


  [`POST ${apiPrefix}/departments`](req, res) {

    res.status(200).end()
  },

  [`GET ${apiPrefix}/departments/:id`](req, res) {
    const { id } = req.params
    const data = queryArray(departments, id, 'id')
    if (data) {
      res.status(200).json(data)
    } else {
      res.status(404).json(NOTFOUND)
    }
  },

  [`DELETE ${apiPrefix}/departments/:id`](req, res) {
    const { id } = req.params
    const data = queryArray(departments, id, 'id')
    if (data) {
      departments = departments.filter(item => item.id !== id)
      res.status(204).end()
    } else {
      res.status(404).json(NOTFOUND)
    }
  },

  [`PATCH ${apiPrefix}/departments/:id`](req, res) {
    const { id } = req.params
    const editItem = req.body
    let isExist = false

    departments = departments.map((item) => {
      if (item.id === id) {
        isExist = true
        return Object.assign({}, item, editItem)
      }
      return item
    })

    if (isExist) {
      res.status(201).end()
    } else {
      res.status(404).json(NOTFOUND)
    }
  },
}
